<template>
  <ElContainer class="member-list-card">
    <ElButton
      v-if="activeTab !== '0'"
      type="warning"
      round
      class="btn-back"
      @click="back"
    >
      <i class="icon-undo2"></i>
      返回主页</ElButton
    >
    <ElTabs
      v-model="activeTab"
      class="tab-step"
      type="card"
      tab-position="bottom"
      @tab-click="next"
    >
      <ElTabPane label="宝宝列表">
        <div class="top-bar">
          <ElUpload
            class="up-excel-button"
            :action="url.excel"
            :headers="headers"
            :show-file-list="false"
            name="excel"
            :on-success="upExcelSuccess"
            :on-error="upExcelError"
          >
            <ElButton type="primary" round plain>批量导入</ElButton>
          </ElUpload>
          <ElButton type="primary" round plain @click="exportExcel"
            >导出表格</ElButton
          >
          <ElButton type="primary" round plain @click="getTemplate"
            >下载模板</ElButton
          >
          <div class="right-options">
            <div class="el-input el-input--suffix">
              <input
                v-model="searchKey"
                type="text"
                autocomplete="off"
                class="el-input__inner search-input"
                placeholder="搜索"
                @keyup.enter="searchList"
              /><span class="el-input__suffix search-button" @click="searchList"
                ><span class="el-input__suffix-inner"
                  ><i
                    :class="[
                      'el-input__icon',
                      isSearching ? 'el-icon-loading' : 'el-icon-search'
                    ]"
                  ></i></span
              ></span>
            </div>
            <!-- <ElButton icon="el-icon-edit">筛选</ElButton> -->
          </div>
        </div>
        <ElTable
          :data="showChildList"
          stripe
          style="width: 100%"
          class="member-list-table"
          default-expand-all
          @selection-change="handleSelectionChange"
        >
          <ElTableColumn align="center" type="selection" width="50">
          </ElTableColumn>
          <ElTableColumn prop="child_name" label="宝宝名字" width="110">
            <template slot-scope="scope">
              <div :class="scope.row.sex === 1 ? 'boy' : 'girl'">
                {{
                  scope.row.child_name.length > 4
                    ? scope.row.child_name.substring(0, 4) + '...'
                    : scope.row.child_name
                }}
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn align="center" prop="birthday_text" label="年龄">
          </ElTableColumn>
          <ElTableColumn align="center" prop="parent_name" label="家长姓名">
            <template slot-scope="scope">{{
              scope.row.parent_name.length > 4
                ? scope.row.parent_name.substring(0, 4) + '...'
                : scope.row.parent_name
            }}</template>
          </ElTableColumn>
          <ElTableColumn align="center" prop="parent_tel" label="联系电话">
          </ElTableColumn>
          <ElTableColumn align="center" prop="masseur_name" label="服务技师">
          </ElTableColumn>
          <ElTableColumn align="center" prop="service_num" label="推拿次数">
          </ElTableColumn>
          <ElTableColumn align="center" prop="level.value" label="会员级别">
          </ElTableColumn>
          <ElTableColumn
            align="center"
            prop="source.source_name"
            label="客户来源"
          >
          </ElTableColumn>
          <ElTableColumn type="expand" class="expand-column" width="0">
            <template slot-scope="props">
              <section class="edit-buttons">
                <ElButton
                  round
                  size="mini"
                  @click="gotoCommonDisease(props.row.id)"
                  >常见病咨询</ElButton
                >
                <ElButton
                  round
                  size="mini"
                  @click="gotoHealthCare(props.row.id)"
                  >保健咨询</ElButton
                >
                <ElButton
                  round
                  size="mini"
                  @click="gotoEvaluation(props.row.id)"
                  >体格体质</ElButton
                >
                <ElButton round size="mini" @click="gotoArchive(props.row.id)"
                  >宝宝档案</ElButton
                >
              </section>
            </template>
          </ElTableColumn>
        </ElTable>
        <ElPagination
          v-if="childList.length > 10"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :page-sizes="pageSizes"
          layout="sizes, prev, pager, next"
          :total="childList.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </ElPagination>
      </ElTabPane>
      <ElTabPane label="下一步2">
        <MemberArchive :new-key="newKey" :u-id="id" :leaved="leaved" />
      </ElTabPane>
    </ElTabs>
  </ElContainer>
</template>

<script>
import _ from 'lodash';
import $ from 'jquery';
import Cookie from 'js-cookie';
import {http, catchAppError} from '@/util';
import url from '@/config';
import {pageSizes, menusNavigation} from '@/store';
import MemberArchive from '@/components/member/MemberArchive.vue';
import changeEditStatus from '@/components/member/MemberEditStatus';

export default {
  name: 'MemberList',
  components: {MemberArchive},
  props: {
    activeName: {
      type: Object,
      default: () => ({
        nav: '0'
      })
    }
  },
  data() {
    return {
      activeTab: '0',
      pageSize: 10,
      currentPage: 1,
      leaved: false,
      id: 0,
      newKey: null,
      pageSizes,
      url,
      headers: {
        token: Cookie.get('token')
      },
      childList: [],
      showChildList: [],
      multipleSelection: [],
      searchKey: '',
      isSearching: false
    };
  },
  watch: {
    'activeName.key': function() {
      if (this.activeName.key) {
        this.getData();
      }
    }
  },
  beforeMount() {
    this.getData();
  },
  methods: {
    getData() {
      http
        .post(url.childList)
        .then(res => {
          if (res) {
            this.childList = res;
          } else {
            this.childList = [];
          }
          this.handleCurrentChange(1);
          this.$nextTick(() => {
            $(this.$el)
              .find('.member-list-table tr.expanded + tr')
              .hover(
                // eslint-disable-next-line func-names
                function() {
                  $(this)
                    .addClass('expanded-hover')
                    .prev()
                    .addClass('expanded-hover');
                },
                // eslint-disable-next-line func-names
                function() {
                  $(this)
                    .removeClass('expanded-hover')
                    .prev()
                    .removeClass('expanded-hover');
                }
              );
          });
        })
        .catch(catchAppError);
    },
    handleSelectionChange(val) {
      this.multipleSelection[this.currentPage - 1] = val;
    },
    handleCurrentChange(val) {
      this.showChildList = _.chunk(this.childList, this.pageSize)[val - 1];
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange(1);
      this.multipleSelection = [];
    },
    getTemplate() {
      http
        .post(url.getTemplate, {type: 2})
        .then(res => {
          window.location.href = `//${res.url}`;
        })
        .catch(catchAppError);
    },
    exportExcel() {
      const q = _.reduce(this.multipleSelection, (a, b) => _.concat(a, b), []);
      const idList = q.map(({id}) => id);
      const params = {
        isAll: 2,
        idList: []
      };
      if (idList.length === this.childList.length) {
        params.isAll = 1;
      } else {
        params.idList = idList;
      }
      http
        .post(url.memberExportExcel, params)
        .then(res => {
          window.location.href = `//${res.url}`;
        })
        .catch(catchAppError);
    },
    upExcelSuccess(res) {
      if (res.code === 1) {
        this.$message({
          message: '文件导入成功',
          duration: 5000,
          type: 'success'
        });
        this.uniqueProject = _.uniqueId();
      } else {
        this.$message({
          message: res.msg,
          duration: 5000,
          type: 'error'
        });
      }
    },
    handleMouseOver(e) {
      const tr = e.path.find(e => e.tagName === 'TR');
      if (!tr) return;
      const ptr = tr.previousSibling;
      if (ptr && ptr.classList.contains('expanded')) {
        ptr.classList.add('expanded-hover');
      }
    },
    handleMouseOut(e) {
      const tr = e.path.find(e => e.tagName === 'TR');
      if (!tr) return;
      const ptr = tr.previousSibling;
      if (ptr && ptr.classList.contains('expanded')) {
        ptr.classList.remove('expanded-hover');
      }
    },
    upExcelError() {
      this.$message({
        message: '文件导入失败',
        duration: 5000,
        type: 'error'
      });
    },
    gotoArchive(id) {
      this.id = id;
      this.newKey = _.uniqueId();
      this.next(1);
    },
    gotoEvaluation(id) {
      menusNavigation.navTab('Evaluation', '0', {babyId: id});
    },
    gotoCommonDisease(id) {
      menusNavigation.navTab('CommonDisease', '0', {babyId: id});
    },
    gotoHealthCare(id) {
      menusNavigation.navTab('HealthCare', '0', {babyId: id});
    },
    searchList() {
      if (this.isSearching) return;
      this.isSearching = true;
      http
        .post(url.childList, {key: this.searchKey})
        .then(res => {
          if (res) {
            this.childList = res;
          } else {
            this.childList = [];
          }
          this.handleCurrentChange(1);
          this.isSearching = false;
          this.$nextTick(() => {
            $(this.$el)
              .find('.member-list-table tr.expanded + tr')
              .hover(
                // eslint-disable-next-line func-names
                function() {
                  $(this)
                    .addClass('expanded-hover')
                    .prev()
                    .addClass('expanded-hover');
                },
                // eslint-disable-next-line func-names
                function() {
                  $(this)
                    .removeClass('expanded-hover')
                    .prev()
                    .removeClass('expanded-hover');
                }
              );
          });
        })
        .catch(catchAppError);
    },
    next() {
      this.activeTab = `${+this.activeTab + 1}`;
    },
    back() {
      const tab = menusNavigation.tabs.find(tab => tab.tab === 'MemberList');
      if (!tab.isEditing) {
        this.activeTab = `${this.activeTab - 1}`;
        this.leaved = true;
        return;
      }
      this.$confirm('信息修改未保存，是否确认离开页面？', '', {
        distinguishCancelAndClose: true,
        confirmButtonText: '是',
        cancelButtonText: '否'
      })
        .then(() => {
          this.activeTab = `${this.activeTab - 1}`;
          this.leaved = true;
          changeEditStatus(false);
        })
        .catch(_.noop);
    }
  }
};
</script>

<style lang="scss">
@import '@/assets/css/util.scss';
.el-tabs__content {
  overflow: visible;
}
.member-list-card {
  .el-tabs--card > .el-tabs__header .el-tabs__item {
    display: none;
  }
  .el-tabs__header.is-bottom {
    display: none;
  }
  .tab-step {
    width: 100%;
  }
  .btn-back {
    position: absolute;
    top: -65px;
    right: 30px;
  }
  .el-card {
    margin-bottom: 20px;
  }
  .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #4b90ff;
    color: #fff;
    .boy,
    .girl {
      color: #fff;
    }
    .boy {
      background-position-y: -61px;
    }
    .girl {
      background-position-y: -102px;
    }
  }
  .top-bar {
    padding: 15px 20px;
    background: #fff;
    .up-excel-button {
      display: inline-block;
      margin-right: 10px;
    }
    .right-options {
      float: right;
      .search-input {
        border-radius: 20px;
        border-color: #4b90ff;
        height: 36px;
        line-height: 36px;
      }
      .search-button {
        width: 45px;
        right: 0;
        border-radius: 20px;
        color: #fff;
        background: #4b90ff;
        &:hover {
          cursor: pointer;
        }
        .el-icon-search,
        .el-icon-loading {
          width: 100%;
          font-size: 22px;
        }
      }
    }
  }
  .member-list-table {
    th {
      background-color: #f3f4f6;
    }
    .el-table__expand-column {
      padding: 0;
      .cell {
        display: none;
      }
    }
    td {
      border-bottom: 0;
      .boy {
        color: #5191fa;
        padding-left: 22px;
        background-position-y: 4px;
        background-image: url(../assets/img/sex.png);
        background-repeat: no-repeat;
      }
      .girl {
        color: #f97dbb;
        padding-left: 22px;
        background-position-y: -28px;
        background-image: url(../assets/img/sex.png);
        background-repeat: no-repeat;
      }
    }
    tr {
      cursor: pointer;
    }
    .edit-buttons {
      display: flex;
      justify-content: space-around;
      .el-button {
        background: transparent;
        border-color: #fff;
        color: #fff;
      }
    }
    .expanded-hover td {
      background-color: #4b90ff !important;
      color: #fff !important;
      .boy,
      .girl {
        color: #fff;
      }
      .boy {
        background-position-y: -61px;
      }
      .girl {
        background-position-y: -102px;
      }
    }

    .expanded {
      & + tr {
        display: none;
      }

      & + tr:hover {
        background-color: #4b90ff;
        display: table-row;
      }

      &:hover + tr {
        td {
          background-color: #4b90ff;
        }
        display: table-row;
      }
    }
  }
}
</style>
